#ifndef APISERVER_H
#define APISERVER_H

#include <microhttpd.h>
#include <string>
#include <map>
#include <functional>
#include <jsoncpp/json/json.h>
#include "store.h"
#include "model.h"

namespace nanok {
class APIServer {
public:
    APIServer(Store* store, int port = 8888);
    ~APIServer();    
    bool start();
    void stop();
    std::string getHandler(const std::string url, const std::map<std::string, std::string>& params);
    std::string postHandler(const std::string url, const Json::Value& jsonData);
    // 请求处理例程
    std::string createPod(const Json::Value& jsonData);
    std::string submitTask(const Json::Value& jsonData);
    std::string updateTask(const Json::Value& jsonData);
    std::string updatePod(const Json::Value& jsonData);
    std::string registerNode(const Json::Value& jsonData);

private:
    // 连接信息结构
    struct ConnectionInfo {
        std::string data;
        MHD_PostProcessor* post_processor;
        APIServer* server;
    };
    
    // 静态回调函数 - 修改返回类型为 MHD_Result
    static MHD_Result handleRequest(void* cls, MHD_Connection* connection,
                                   const char* url, const char* method,
                                   const char* version, const char* upload_data,
                                   size_t* upload_data_size, void** con_cls);
    
    static MHD_Result iteratePost(void* coninfo_cls, MHD_ValueKind kind,
                                 const char* key, const char* filename,
                                 const char* content_type, const char* transfer_encoding,
                                 const char* data, uint64_t off, size_t size);
    
    // 实例方法
    // MHD_Result processRequest(MHD_Connection* connection, const std::string& method,
    //                          const std::string& url, const std::string& upload_data);
    
    // 解析URL参数
    static MHD_Result parseQueryString(void *cls, MHD_ValueKind kind, 
                               const char *key, const char *value);
    
    Store* store_;
    int port_;
    MHD_Daemon* daemon_;
    // GetHandler getHandler_;
    // PostHandler postHandler_;
};

}

#endif // APISERVER_H